package com.qcby.proxy;

import com.qcby.annotation.Transactional;
import com.qcby.manager.TransactionManager;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * @author 程子强
 * @Description
 * @date 2025/7/10 8:44
 */
public class JdkTransactionHandler implements InvocationHandler {
    private Object  target;

    public JdkTransactionHandler(Object target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        //获取目标方法
        Method targetMethod = target.getClass().getMethod(method.getName(), method.getParameterTypes());
        //先判断该方法或该方法所在类上是否有事务注解(但是因为传过来的是接口，如果注解加在实现类上那么if就无法生效所以还要判断实现类的方法)
        if (method.isAnnotationPresent(Transactional.class) ||
                method.getDeclaringClass().isAnnotationPresent(Transactional.class)||targetMethod.isAnnotationPresent(Transactional.class) ||
                targetMethod.getDeclaringClass().isAnnotationPresent(Transactional.class)) {
            try {
                TransactionManager.begin();
                Object result = method.invoke(target, args);
                TransactionManager.commit();
                return result;
            } catch (Exception e) {
                TransactionManager.rollback();
                throw e;
            }
        }
        //如果没有则正常执行
        return method.invoke(target, args);
    }
}
